/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.members;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.*;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.SearchOperator;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.service.members.MemberService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: MembersController <br/>
 * Function: member [会员信息] <br/>
 * date: 2018-12-04 11:16:11 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/members/members")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_member:read",name ="会员信息",deleteAble = false)
public class MembersController extends BaseManagementController{

	@Autowired
	private MemberService memberService;
	@Autowired
    private DistrictService districtService;
	@Autowired
    private BranchService branchService;

	private final String [] keys = {"id","phone","name","gender","cardNo","birthdayType","birthday","source","consumeCount","consumeAmount",
            "consumeTime","state","createAt","count","createAt","branchName"};

    @RequiresPermissions("management_member:show")
    @PermissionInfo(code = "management_member:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        String no = searchable.getValue("no_eq");
        List<Long> ids = null;
        if(StringUtils.isNotBlank(no)){
             ids = memberService.getIdsByCardNo(no,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        }
        if(CollectionUtils.isNotEmpty(ids)){
            searchable.addSearchFilter("id", SearchOperator.in,ids);
        }


        searchable.removeSearchFilter("no_eq");
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<Member> memberPage = memberService.findAll(searchable);
        if (CollectionUtils.isNotEmpty(memberPage.getContent())){
            for (Member member : memberPage.getContent()) {
                member.setCount(memberService.getCardCount(member.getId(),CurrentAccountUtils.getAuthenticatedMerchantGroupID()));
            }
        }
        QyMap map = QyMap.map("memberPage",JSONUtils.include(memberPage,new Class[]{Gender.class}, keys));
        initFormDate(map);
        return ok("查询成功",map );
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("member",JSONUtils.include(new Member(), keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_member:create")
    @PermissionInfo(code = "management_member:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid Member member, BindingResult bindingResult){
//        if(memberService.exists(buildExists(null, "no", member.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        memberService.save(member);
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute Member member){
        member.setCount(memberService.getCardCount(member.getId(),CurrentAccountUtils.getAuthenticatedMerchantGroupID()));
        return ok("查询成功", JSONUtils.include(member,new Class[]{Gender.class}, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute Member member){
        QyMap map=QyMap.NEW();
        map.setv("member",JSONUtils.include(member, keys));
        initFormDate(map); //TODO 如果没有需要初始化的数据，测则删除该行
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_member:update")
    @PermissionInfo(code = "management_member:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid Member member,BindingResult bindingResult){
//        if(memberService.exists(buildExists(null, "no", member.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        memberService.update(member);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_member:destory")
    @PermissionInfo(code = "management_member:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        memberService.logicDelete(id);
        return ok("删除成功", null);
    }

    /**
     * 获取会员卡详情
     * @param id
     * @return
     */
    @GetMapping("/getMemberCard")
    public Object getMemberCard(Long id){
        List<MemberCard> cardList = memberService.getMemberCard(id,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("查询成功", JSONUtils.include(cardList,new Class[]{MemberCardState.class},"id","no","type.id:typeId","type.name:typeName","type.hasConsumeRecharge:hasConsumeRecharge","type.hasVipPrice:hasVipPrice","amount","giftAmount","point","state","startTime","endTime"));
    }

    @GetMapping("/getVipRecord")
    public Object getVipRecord(Long id,Searchable searchable){
        searchable.addSort(Sort.Direction.DESC,"createAt");
        Page<VipRecord> recordPage = memberService.getVipRecord(id,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),searchable);
        QyMap map = QyMap.map("recordPage",JSONUtils.include(recordPage,new Class[]{VipRecordType.class,MemberCardState.class, RechargeSource.class,PayType.class},"id","uuid","type","operatorName","vipName","vipPhone","cardNo","cardMode",
                "cardType","deposit","amount","giftValue","giftPoint","beforeValue","beforeGift","beforPoint","afterValue","afterGift",
                "afterPoint","platform","targetNo","cardState","payType","undoTime","orderNo","castBack","backDesc","remark","createAt","branchName"));

        //门店
        map.setv("districts",getDistricts());
        //操作类型
        map.setv("types",VipRecordType.values());
        map.setv("memberCards", JSONUtils.include(memberService.getMemberCard(id,CurrentAccountUtils.getAuthenticatedMerchantGroupID()),"id","no","type.id:typeId","type.name:typeName","type.hasConsumeRecharge:hasConsumeRecharge","type.hasVipPrice:hasVipPrice","amount","giftAmount","point","state","startTime","endTime"));
        return ok("查询成功", map);
    }



    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            Member member = memberService.findById(Long.valueOf(id));
            model.addAttribute(member);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //入会门店
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("parentId_eq",0L);
        List<District> districtList = districtService.findWithSort(searchable);

        if(CollectionUtils.isNotEmpty(districtList)){
            searchable = SearchableUtils.newSearchableWithMerchantFilter();
            List<Branch> branchList =branchService.findWithSort(searchable);
            districtList.get(0).setChildren((JSONArray)JSONUtils.include(branchList,"id","name","districtId","state"));
        }
        qyMap.setv("districts",districtList);

        //入会渠道
        qyMap.setv("createSourceTypes", CreateSourceType.values());
    }

}